package linux

import (
	"fmt"
	"gitee.com/mangenotework/commander/common/cmd"
	"log"
	"os"
	"os/exec"
	"strings"
	"syscall"
)

// 是否安装nginx
// nginx -v是向stderr写入了数据，所以从stdout是拿不到数据的
func HasNginx() (bool, string) {
	cmd := exec.Command("nginx", "-v")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Setpgid: true,
	}

	out, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
	rse := string(out)
	if strings.Index(rse, "nginx version") == -1 {
		return false, "未安装Nginx"
	}
	return true, rse
}

// apt 安装nginx
func AptInstallNginx() string {
	rse := ""

	if IsApt() {
		// 更新源
		stp1 := cmd.LinuxSendCommand("sudo apt-get update -y")
		log.Println(stp1)
		rse += stp1

		// 安装nginx
		stp2 := cmd.LinuxSendCommand("sudo apt-get install nginx -y")
		log.Println(stp2)
		rse += stp2

		// 查看安装
		stp3 := cmd.LinuxSendCommand("nginx -v")
		log.Println(stp3)
		rse += stp3
	}

	return rse
}

// yum 安装nginx
func YumInstallNginx() string {
	rse := ""

	if IsYum() {
		// 下载 epel-release
		stp1 := cmd.LinuxSendCommand("sudo yum -y install epel-release")
		log.Println(stp1)
		rse += stp1

		// 更新源
		stp2 := cmd.LinuxSendCommand("sudo yum -y update")
		log.Println(stp2)
		rse += stp2

		// 安装
		stp3 := cmd.LinuxSendCommand("sudo yum -y install nginx")
		log.Println(stp3)
		rse += stp3

		// 查看安装
		stp4 := cmd.LinuxSendCommand("nginx -v")
		log.Println(stp4)
		rse += stp4
	}

	return rse
}

// 卸载nginx
func RemoveNginx() string {
	rse := ""

	if IsApt() {
		// sudo apt-get --purge -y remove nginx
		stp1 := cmd.LinuxSendCommand("sudo apt-get --purge -y remove nginx")
		log.Println(stp1)
		rse += stp1

		// sudo apt-get --purge -y remove nginx-common
		stp2 := cmd.LinuxSendCommand("sudo apt-get --purge -y remove nginx-common")
		log.Println(stp2)
		rse += stp2

		// sudo apt-get --purge -y remove nginx-core
		stp3 := cmd.LinuxSendCommand("sudo apt-get --purge -y remove nginx-core")
		log.Println(stp3)
		rse += stp3
	}

	if IsYum() {
		// yum remove -y nginx
		stp1 := cmd.LinuxSendCommand("yum remove -y nginx")
		log.Println(stp1)
		rse += stp1
	}

	return rse
}

func DeployedNginx() string {
	rse := AptInstallNginx()
	rse = YumInstallNginx()
	return rse
}